package wsi.gui.resolve;

import java.io.File;

import javafx.event.EventHandler;
import javafx.scene.input.MouseEvent;

import org.rygh.core.util.UIo;
import org.rygh.gui.comp.Table;
import org.rygh.gui.model.Presenter;
import org.rygh.gui.model.callback.Callback;
import org.rygh.gui.window.Window;

import wsi.exp.exp5.JudgeFileManager;
import wsi.function.Function;
import wsi.gui.resolve.model.FunctionFileData;
import wsi.gui.resolve.model.FunctionFileTuple;
import wsi.gui.resolve.model.FunctionStatTuple;

public class FunctionFilePresenter extends Presenter {

	public interface Display extends Presenter.Display {

	}

	private final FunctionFileData data = new FunctionFileData();

	private Callback<FunctionFileTuple> callback;

	private FunctionStatTuple item;

	public FunctionFilePresenter() {
		display = new Window("Judged Files Reviewer",
				new FunctionFileView(this), 640, 480);

		getTable().setData(data);

		bind();
	}

	@Override
	protected void bind() {
		getTable().setOnMouseClicked(new EventHandler<MouseEvent>() {

			@Override
			public void handle(MouseEvent event) {
				if (event.getClickCount() != 2)
					return;

				FunctionFileTuple item = getTable().getSelectionModel()
						.getSelectedItem();

				if (item == null)
					return;

				if (callback != null)
					callback.call(item);
			};
		});
	}

	private Table<FunctionFileTuple> getTable() {
		return invoke("display.view.tableView.table");
	}

	public void refresh() {
		data.clear();

		if (item == null)
			return;

		Function function = item.getFunction();
		JudgeFileManager jm = new JudgeFileManager(function);

		for (File file : jm.getJudgedFiles()) {
			String fname = UIo.getFileNameWithoutExtension(file.getName());
			fname = fname.substring(0, fname.indexOf(JudgeFileManager._JUDGED));

			File xmlFile = new File(file.getParent(), String.format("%s.xml",
					fname));

			FunctionFileTuple tuple = new FunctionFileTuple(item.getFunction(),
					xmlFile, file);
			data.add(tuple);
		}

	}

	public void setCallback(Callback<FunctionFileTuple> callback) {
		this.callback = callback;
	}

	public void setItem(FunctionStatTuple item) {
		assert item != null;
		this.item = item;
	}

}
